# -*- coding: utf-8 -*-
# @Time : 2019/2/16 10:34
# @Author : Chilson

import smtplib
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.header import Header


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def sent_email_by_smtp(msg, subject, from_addr, password, to_addr):
    """通过smtp发送邮件

    Args:
        msg: str 邮件内容
        subject: str 邮件主题
        from_addr: str 发邮件的邮箱
        password: str 发邮件的邮箱授权密码
        to_addr: str 接受邮件的邮箱
    """
    # Email地址和口令
    from_addr = from_addr
    password = password
    # 收件人地址
    to_addr = to_addr
    # SMTP服务器地址
    smtp_server = 'smtp.%s' % to_addr.split('@')[1]

    server = smtplib.SMTP(smtp_server, 25)  # SMTP协议默认端口是25
    server.set_debuglevel(1)
    server.login(from_addr, password)

    msg['From'] = _format_addr(u'报警员 <%s>' % from_addr)
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
    msg['Subject'] = Header(subject, 'utf-8').encode()
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()


if __name__ == '__main__':
    msg = MIMEText(u'你还好吗？', 'plain', 'utf-8')  # 邮件内容
    subject = u'测试报警，别慌...'  # 邮件主题
    from_addr = '***'  # 发送地址
    password = '***'  # SMTP协议客户端授权码
    to_addr = '***'  # 接收地址
    sent_email_by_smtp(msg, subject, from_addr, password, to_addr)